package main

import (
	"booking/common/logger"
	"booking/internal/app/router"
	"booking/models"
	"context"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"booking/config"
	"booking/locales"
)

func main() {
	time.Local = time.UTC
	config.Init()
	models.Database()
	models.Redis()
	locales.Init()
	// 启动 HTTP 服务
	r := router.Router()
	srv := &http.Server{
		Addr:    ":6302",
		Handler: r,
	}

	// 启动服务并监听信号
	go func() {
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			logger.Fatalf("listen: %s\n", err)
		}
	}()
	logger.Println("Server started on :6302")

	// 等待信号（如 SIGINT、SIGTERM）
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	logger.Println("Shutting down server...")

	// 创建一个 5 秒的超时时间来优雅地关闭服务
	ctx, cancel := context.WithTimeout(context.Background(), 50*time.Second)
	defer cancel()

	if err := srv.Shutdown(ctx); err != nil {
		log.Fatal("Server forced to shutdown:", err)
	}
	logger.Println("Server exiting gracefully")
}
